package control;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;


import jxl.read.biff.BiffException;
import jxl.write.WriteException;

import persistence.XlsStatistic;
import view.components.Icons;

public class ExportLoanStatisticHandler {
	JFileChooser fileChooser;
	String fileName = File.separator + "xls";
	
	public ExportLoanStatisticHandler(){
		fileChooser = new JFileChooser(new File(fileName));
		fileChooser.removeChoosableFileFilter(fileChooser.getChoosableFileFilters()[0]);
		fileChooser.addChoosableFileFilter(new XLSFilter());
	}

	public void startExport(Date start, Date end){
		try{
			File file = askForDestinationFile();
			XlsStatistic statistics = new XlsStatistic("xls/Template.xls", file.getAbsolutePath());
			statistics.setRange(start, end);
			try {
				statistics.createXLS();
				StatusMessageHandler.putMessage("Statistik erfolgreich exportiert");
				statistics.openXls();
			} catch (WriteException e) {
				StatusMessageHandler.putMessage("Konnte \""+ file.getAbsolutePath() + "\" nicht speichern", Icons.ERROR);
			} catch (IOException e) {
				StatusMessageHandler.putMessage("Konnte \""+ file.getAbsolutePath() + "\" nicht speichern", Icons.ERROR);
			} catch (BiffException e) {
				StatusMessageHandler.putMessage("Konnte \"xls/Template.xls\" nicht speichern", Icons.ERROR);
			}
			
			
		} catch (IllegalArgumentException e) {
			StatusMessageHandler.putMessage("Erstellen der Statistik abgebrochen");
		}
	}
	
	private File askForDestinationFile() throws IllegalArgumentException{
		if (fileChooser.showSaveDialog(null)==JFileChooser.APPROVE_OPTION) {
			File file = fileChooser.getSelectedFile();
			if(!fileChooser.getFileFilter().accept(file)){
				file=new File(file.getAbsoluteFile()+".xls");
			}
			return file;
		}
		throw new IllegalArgumentException();
	}
	
	private class XLSFilter extends FileFilter {
		public boolean accept(File file) {
			if(file.isDirectory()){
				return true;
			}
			String filename = file.getName();
			return filename.endsWith(".xls");
		}

		public String getDescription() {
			return "*.xls";
		}
	}
}
